#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#include <sys/mman.h>

#define MAXMSG 1024
#define N 100

int main()
{   int id;
    int i;
    unsigned char * addr;

	id=shm_open("var",O_RDWR|O_CREAT,0777);

    if( id == -1 ) {
    	printf("id %i errno %i \n",id,errno);
    	switch (errno)
		{   case EACCES: printf("eacces\n"); break;
       	 	case EEXIST: printf("eexist\n"); break;
		case EINVAL: printf("einval\n"); break;
        	case EINTR: printf("eintr\n"); break;
        	case ELOOP: printf("eloop\n"); break;
        	case EMFILE: printf("emfile\n"); break;
        	case ENAMETOOLONG: printf("enametoolong\n"); break;
        	case ENFILE: printf("enfile\n"); break;
        	case ENOENT: printf("enoent\n"); break;
        	case ENOSPC: printf("enospc\n"); break;
        	case ENOSYS: printf("enosys\n"); break;
    	}
    	return 0;
    }
 

     /* Set the memory object's size */
    if( ftruncate( id, N*sizeof( *addr ) ) == -1 ) {
        fprintf( stderr, "ftruncate: %s\n",
            strerror( errno ) );
        return EXIT_FAILURE;
    }


    /* Map the memory object */
    addr = mmap( 0, N*sizeof( char ),
            PROT_READ | PROT_WRITE,
            MAP_SHARED, id, 0 );
    if( addr == MAP_FAILED ) {
        fprintf( stderr, "mmap failed: %s\n",
            strerror( errno ) );
        return EXIT_FAILURE;
    }

    /* Write to shared memory */
    for (i=0;i<N;i++)
    	addr[i] = i;

    for (i=0;i<N;i++)
    	printf("&addr=%lu addr[%i]=%i\n",&addr[i],i,addr[i]);

    /*
     * The memory object remains in
     * the system after the close
     */
    close( id );

}
